<?php

/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace common\rest\actions\auth;

use Yii;
use yii\base\Model;
use yii\helpers\Url;
use yii\web\ServerErrorHttpException;
use yii\rest\Action;
use common\rest\statics\ResponseDatum;
use common\rest\base\WxException;
use common\rest\statics\OperationResult;

/**
 * CreateAction implements the API endpoint for creating a new model from the given data.
 *
 * For more details and usage information on CreateAction, see the [guide article on rest controllers](guide:rest-controllers).
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class CreateAction extends Action {

    /**
     * @var string the scenario to be assigned to the new model before it is validated and saved.
     */
    public $scenario = Model::SCENARIO_DEFAULT;

    /**
     * @var string the name of the view action. This property is need to create the URL when the model is successfully created.
     */
    public $viewAction = 'view';

    /**
     * auth id
     * @var string 
     */
    public $authIdAttribute = "user_id";

    /**
     * Creates a new model.
     * @return \yii\db\ActiveRecordInterface the model newly created
     * @throws ServerErrorHttpException if there is any error when creating the model
     */
    public function run() {
        try {
            $model = new $this->modelClass([
                'scenario' => $this->scenario,
            ]);
            $params = Yii::$app->getRequest()->getBodyParams();
            $model->load($params);
            $model->{$this->authIdAttribute} = Yii::$app->user->id;
            if ($model->save()) {
                return ResponseDatum::getSuccessDatum(['msg' => Yii::t('app.c2', 'Operation completed successfully!')], $model);
            } elseif ($model->hasErrors()) {
                throw new WxException($model->getFirstErrorSummary(), OperationResult::ERROR_600, $params, ['errors' => $model->errors]);
            } else {
                throw new WxException(Yii::t('app.c2', 'Error: Operation can not finish!!'), OperationResult::ERROR_INTERNAL, $params, null);
            }
        } catch (WxException $ex) {
            return ResponseDatum::getErrorDatum([
                        'code' => $ex->getCode(),
                        'msg' => $ex->getMessage(),
                        'extraData' => $ex->extraData,
                            ], $ex->data);
        }
    }

}
